package com.zhxx.book.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zhxx.book.entity.User;
import com.zhxx.book.service.IUserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @Description: 暂时弃用
 * @Author Alex
 * @Date 2022-11-28 16:15
 */
@RestController
@RequestMapping("/login")
public class LoginController {
   @Autowired
   private RestTemplate restTemplate;
   @Autowired
   private IUserService userService;

   @PostMapping
   public User login(@RequestBody User user) {
      System.out.println("用户信息：" + user);
      /* 1-整理数据，需要如下 */
      // 请求地址
      String url = "https://api.weixin.qq.com/sns/jscode2session";
      //小程序 appId
      String appid = "wx616a1663bc6b5f26";
      //小程序 appSecret
      String secret = "92d560100960af3a9a671fd19d0f72b8";
      //登录时获取的 code
      String js_code = user.getCode();
      // 授权类型，此处只需填写 authorization_code
      String grant_type = "authorization_code";
      /* 2-拼接地址 */
      String path = url + "?appid=" + appid + "&secret=" + secret + "&js_code=" + js_code + "&grant_type=" + grant_type;
      System.out.println("拼接后的请求路径：" + path);
      /* 3-使用HttpClientUtil工具类发送get请求拼接后的地址得到json结果 */
      String res = restTemplate.getForObject(path, String.class);
      System.out.println("请求结果：" + res);
      /* 4-使用fastjson解析json结果得到openid */
      JSONObject jsonObject = JSONUtil.parseObj(res);
      String openid = jsonObject.get("openid").toString();
      System.out.println("openid是：" + openid);

      User userEntity = userService.getById(openid);
      if(ObjectUtil.isEmpty(userEntity)) {
         userService.save(user);
      }

      return user;
   }
}
